package parser;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2023年07月13日 9:10
 */
public class PrintDomParser {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(PrintDomParser.class.getClassLoader().getResourceAsStream("students.xml"));
            Element root = document.getDocumentElement();
            print(root);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void print(Element root) {
        // 打印开始标签
        System.out.print("<" + root.getTagName());

        // 打印标签属性
        NamedNodeMap attributes = root.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            System.out.print(" " + attributes.item(i));
        }
        System.out.print(">");

        // 打印标签体
        NodeList childNodes = root.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node node = childNodes.item(i);
            // 如果是元素节点,使用递归操作
            if(node.getNodeType() == Node.ELEMENT_NODE){
                Element ele = (Element) node;
                print(ele);
            }
            // 如果是文本节点,直接打印节点内容
            if(node.getNodeType() == Node.TEXT_NODE){
                System.out.print(node.getTextContent());
            }
        }

        // 打印结束标签
        System.out.print("</"+root.getTagName()+">");
    }

}
